const connection = require('../app/databases');
const { removeImg } = require('../utils/removeFiles-handle');

class ProductService {
  // 通过名称获取商品信息
  async getProductInformationByName(name) {
    try {
      const statement = `SELECT * FROM products WHERE name like '%${name}%';`;
      const [result] = await connection.execute(statement);
      
      return result;
    } catch (error) {
      return error.message;
    }    
  }

  // 获取商品信息
  async getProductInformationByLimit(offset, size) {
    try {
      const statement = `SELECT * FROM products LIMIT ?, ?;`;
      const [result] = await connection.execute(statement, [offset, size]);
      
      return result;
    } catch (error) {
      return error.message;
    }    
  }

  // 添加商品成功
  async addProductInformation(name, price, introduce, details, imagePatch) {
    try {
      const statement = `INSERT INTO products (name, price, introduce, details, imagePatch, createTime) VALUES(?, ?, ?, ?, ?, NOW());`;
      const [result] = await connection.execute(statement, [name, price, introduce, details, imagePatch]);

      if (result.affectedRows) {
        return '商品数据添加成功';
      }
    } catch (error) {
      return error.message;
    }    
  }

  // 修改商品信息
  async changeProductInformation(id, name, price) {
    try {
      const statement = `UPDATE products SET name=?,  price=? WHERE id=?;`;
      const [result] = await connection.execute(statement, [name, price, id]);

      return 'success';
    } catch (error) {
      return error.message;
    }
  }

  // 删除商品数据
  async deleteProductInformation(id, imagePatch) {
    try {
      const statement = `DELETE FROM products WHERE id=?;`;
      const [result] = await connection.execute(statement, [id]);

      // 删除图片文件
      removeImg(imagePatch);

      return 'success';
    } catch (error) {
      return error.message;
    }
  }
}

module.exports = new ProductService();